package com.tuanzi.loan.business.repository.product.product.impl;

import com.tuanzi.loan.business.repository.product.product.custom.LoanProductConsumeRecordRepositoryCustom;
import com.tuanzi.loan.core.repository.JOOQBaseRepository;
import com.tuanzi.loan.vo.request.product.product.LoanProductConsumeSearchRequest;
import com.tuanzi.loan.vo.response.product.product.LoanProductConsumeSearchResponse;
import org.jooq.Record;
import org.jooq.RecordMapper;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import static com.tuanzi.loan.generated.jooq.loan.tables.LoanProductConsumeRecord.LOAN_PRODUCT_CONSUME_RECORD;

/**
 * @Auther: hequnayu
 * @Date: 2019/7/15 15:48
 * @Description:
 */
public class LoanProductConsumeRecordRepositoryImpl extends JOOQBaseRepository implements LoanProductConsumeRecordRepositoryCustom {


    @Override
    protected TableImpl getTable() {
        return LOAN_PRODUCT_CONSUME_RECORD;
    }

    @Override
    public Page<LoanProductConsumeSearchResponse> list(LoanProductConsumeSearchRequest searchRequest, Pageable pageable) {
        eq(LOAN_PRODUCT_CONSUME_RECORD.PRODUCT_ID, searchRequest.getProduct_id());
        return search(pageable, new LoanProductConsumeRecordSearchResponseRecordMapper());
    }

    @Override
    public Double countConsumeMoneyByProdid(Long prdid) {
        return dslContext.select(DSL.sum(LOAN_PRODUCT_CONSUME_RECORD.CONSUME_MONEY)).from(LOAN_PRODUCT_CONSUME_RECORD).where(LOAN_PRODUCT_CONSUME_RECORD.PRODUCT_ID.eq(prdid)).fetchOneInto(Double.class);
    }

    private final class LoanProductConsumeRecordSearchResponseRecordMapper implements RecordMapper<Record, LoanProductConsumeSearchResponse> {

        @Override
        public LoanProductConsumeSearchResponse map(Record record) {
            LoanProductConsumeSearchResponse response = new LoanProductConsumeSearchResponse();
            response.setId(record.get(LOAN_PRODUCT_CONSUME_RECORD.ID));
            response.setProduct_id(record.get(LOAN_PRODUCT_CONSUME_RECORD.PRODUCT_ID));
            response.setUv_value(record.get(LOAN_PRODUCT_CONSUME_RECORD.UV_VALUE));
            response.setUv_num(record.get(LOAN_PRODUCT_CONSUME_RECORD.UV_NUM));
            response.setConsume_money(record.get(LOAN_PRODUCT_CONSUME_RECORD.CONSUME_MONEY));
            response.setCreate_date(record.get(LOAN_PRODUCT_CONSUME_RECORD.CREATE_DATE));
            return response;
        }
    }
}
